<template>
  <div id="login">
    <nav-bar>
      <template v-slot:default>用户登录</template>
    </nav-bar>
    <div class="form">
      <van-form @submit="onSubmit">
        <van-field
          v-model="email"
          name="邮箱"
          label="邮箱"
          placeholder="邮箱"
          :rules="[{ required: true, message: '请填写正确的邮箱' }]"
        />

        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />

        <div class="link-register" @click="$router.push({ path: '/register' })">
          没有账号，立即注册
        </div>
        <div style="margin: 16px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            color="#44b883"
            >登录</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import NavBar from "components/common/navbar/NavBar";
import { login } from "network/user";
import { Notify, Toast } from "vant";
import { useRouter } from "vue-router";
import { ref, reactive, toRefs, useSSRContext } from "vue";
import { useStore } from "vuex";
export default {
  name: "Login",
  setup() {
    const store = useStore();
    const router = useRouter();
    const userinfo = reactive({
      email: "",
      password: "",
    });

    const onSubmit = () => {
      login(userinfo).then((res) => {
        // 将token保存在本地
        window.localStorage.setItem("token", res.access_token);
        // 在vuex isLogin
        store.commit("setIsLogin", true);
        Toast.success("登录成功");
        userinfo.email = "";
        userinfo.password = "";
        setTimeout(() => {
          router.go(-1);
        }, 500);
      });
    };

    return { ...toRefs(userinfo), onSubmit };
  },
  components: {
    NavBar,
  },
};
</script>

<style scoped lang="scss">
#login {
  .form {
    margin-top: 100px;
    .link-register {
      margin-top: 10px;
      font-size: 14px;
      color: #44b883;
    }
  }
}
</style>